package com.zbar.lib;

import java.io.IOException;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Point;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.next.intf.ITaskListener;
import com.next.net.SHPost;
import com.next.net.SHTask;
import com.sky.widget.SHDialog;
import com.sky.widget.SHToast;
import com.sky.widget.sweetdialog.SweetDialog;
import com.sky.widget.sweetdialog.SweetDialog.OnSweetClickListener;
import com.sky.zzh.R;
import com.sky.zzh.SHContainerActivity;
import com.sky.zzh.devicemanager.ActiveDeviceFragment;
import com.sky.zzh.util.CommonUtil;
import com.sky.zzh.util.ConfigDefinition;
import com.sky.zzh.util.UserInfoManager;
import com.sky.zzh.view.SHEditTextNoClear;
import com.zbar.lib.camera.CameraManager;
import com.zbar.lib.decode.CaptureActivityHandler;
import com.zbar.lib.decode.InactivityTimer;

/**
 * 作者: 陈涛(1076559197@qq.com)
 * 
 * 时间: 2014年5月9日 下午12:25:31
 * 
 * 版本: V_1.0.0
 * 
 * 描述: 扫描界面
 */
public class CaptureActivity extends Activity implements Callback, ITaskListener {

	private CaptureActivityHandler handler;
	private boolean hasSurface;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.50f;
	private boolean vibrate;
	private int x = 0;
	private int y = 0;
	private int cropWidth = 0;
	private int cropHeight = 0;
	private LinearLayout mContainer = null;
	private RelativeLayout mCropLayout = null;
	private SHEditTextNoClear mEtDeviceNum;
	private Button mBtnConnect, mBtnBack;
	SHPost activeTask, connectTask;

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public int getCropWidth() {
		return cropWidth;
	}

	public void setCropWidth(int cropWidth) {
		this.cropWidth = cropWidth;
	}

	public int getCropHeight() {
		return cropHeight;
	}

	public void setCropHeight(int cropHeight) {
		this.cropHeight = cropHeight;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_scan);
		// 初始化 CameraManager
		CameraManager.init(getApplication());
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);

		mContainer = (LinearLayout) findViewById(R.id.capture_containter);
		mCropLayout = (RelativeLayout) findViewById(R.id.capture_crop_layout);
		mEtDeviceNum = (SHEditTextNoClear) findViewById(R.id.et_device_num);
		mBtnConnect = (Button) findViewById(R.id.btn_connect);
		mBtnBack = (Button) findViewById(R.id.btn_back);

		ImageView mQrLineView = (ImageView) findViewById(R.id.capture_scan_line);
		ScaleAnimation animation = new ScaleAnimation(1.0f, 1.0f, 0.0f, 1.0f);
		animation.setRepeatCount(-1);
		animation.setRepeatMode(Animation.RESTART);
		animation.setInterpolator(new LinearInterpolator());
		animation.setDuration(1200);
		mQrLineView.startAnimation(animation);

		setListeners();

	}

	boolean flag = true;

	protected void light() {
		if (flag == true) {
			flag = false;
			// 开闪光灯
			CameraManager.get().openLight();
		} else {
			flag = true;
			// 关闪光灯
			CameraManager.get().offLight();
		}

	}

	private void setListeners() {
		mBtnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		mBtnConnect.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (CommonUtil.isEmpty(mEtDeviceNum.getText().toString().trim())) {
					SHToast.showToast(CaptureActivity.this, "请输入设备序列号");
					return;
				}
				SHDialog.ShowProgressDiaolg(CaptureActivity.this);
				connectTask = new SHPost();
				connectTask.setUrl(ConfigDefinition.URL + "user/RegisterUserDevice");
				connectTask.setListener(CaptureActivity.this);
				connectTask.getTaskArgs().put("UserID", UserInfoManager.getInstance().getUserId());
				connectTask.getTaskArgs().put("UUID", mEtDeviceNum.getText().toString().trim());
				connectTask.getTaskArgs().put("Description", getIntent().getStringExtra("des"));
				connectTask.start();
			}
		});
	}

	private void active() {
		activeTask = new SHPost();
		activeTask.setUrl(ConfigDefinition.URL + "user/ActivateUserDevice");
		activeTask.setListener(CaptureActivity.this);
		activeTask.getTaskArgs().put("UserID", UserInfoManager.getInstance().getUserId());
		activeTask.getTaskArgs().put("UUID", mEtDeviceNum.getText().toString().trim());
		activeTask.start();
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onResume() {
		super.onResume();
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.capture_preview);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	public void handleDecode(String result) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
		// Toast.makeText(getApplicationContext(), result,
		// Toast.LENGTH_SHORT).show();
		mEtDeviceNum.setText(result);

		// 连续扫描，不发送此消息扫描一次结束后就不能再次扫描
		handler.sendEmptyMessage(R.id.restart_preview);
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);

			Point point = CameraManager.get().getCameraResolution();
			int width = point.y;
			int height = point.x;

			int x = mCropLayout.getLeft() * width / mContainer.getWidth();
			int y = mCropLayout.getTop() * height / mContainer.getHeight();

			int cropWidth = mCropLayout.getWidth() * width / mContainer.getWidth();
			int cropHeight = mCropLayout.getHeight() * height / mContainer.getHeight();

			setX(x);
			setY(y);
			setCropWidth(cropWidth);
			setCropHeight(cropHeight);

		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(CaptureActivity.this);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public Handler getHandler() {
		return handler;
	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

	@Override
	public void onTaskFinished(SHTask task) throws Exception {
		// TODO Auto-generated method stub
		System.out.println(task.getResult());
		JSONObject json = new JSONObject(task.getResult().toString());
		if (task == connectTask) {
			active();
		} else if (task == activeTask) {
			SHDialog.dismissProgressDiaolg();
			if ("200".equals(json.optString("ReturnCode"))) {
				new SweetDialog(CaptureActivity.this).setTitleText("提示").setContentText("已成功关联您的设备，是否需要现在激活设备？").showCancelButton(true).setConfirmClickListener(new OnSweetClickListener() {

					@Override
					public void onClick(SweetDialog sweetAlertDialog) {
						// TODO Auto-generated method stub
						sweetAlertDialog.dismiss();
						Intent intent = new Intent(CaptureActivity.this, SHContainerActivity.class);
						intent.putExtra("class", ActiveDeviceFragment.class.getName());
						intent.putExtra("UUID", mEtDeviceNum.getText().toString().trim());
						startActivity(intent);
						finish();
					}
				}).setCancelClickListener(new OnSweetClickListener() {

					@Override
					public void onClick(SweetDialog sweetAlertDialog) {
						// TODO Auto-generated method stub
						sweetAlertDialog.dismiss();
						UserInfoManager.getInstance().setUUID(mEtDeviceNum.getText().toString().trim());
						UserInfoManager.getInstance().sync(CaptureActivity.this, true);
						finish();
					}
				}).setCancelText("不需要").setConfirmText("激活").show();
			} else {
				new SweetDialog(CaptureActivity.this, SweetDialog.ERROR_TYPE).setTitleText("提示").setContentText("关联的设备不存在").show();
			}
		}
	}

	@Override
	public void onTaskFailed(SHTask task) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTaskUpdateProgress(SHTask task, int count, int total) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTaskTry(SHTask task) {
		// TODO Auto-generated method stub

	}
}